package src.数据结构.栈;

public class 后缀表达式 {
    public static void main(String[] args) {
        // 3*(17-15)+18/6
        String[] str = {"3", "17", "15", "-", "*", "18", "6", "/", "+"};

        caculate(str);
    }

    private static void caculate(String[] str) {
        Stack<String> stack = new Stack<>();
        int n1, n2, n3;
        for (String s : str) {
            switch (s) {
                case "+":
                    n1 = Integer.parseInt(stack.pop()); // 第二个操作数
                    n2 = Integer.parseInt(stack.pop()); // 第一个操作数
                    n3 = n2 + n1;
                    stack.push(String.valueOf(n3));
                    break;
                case "-":
                    n1 = Integer.parseInt(stack.pop());
                    n2 = Integer.parseInt(stack.pop());
                    n3 = n2 - n1;
                    stack.push(String.valueOf(n3));
                    break;
                case "*":
                    n1 = Integer.parseInt(stack.pop());
                    n2 = Integer.parseInt(stack.pop());
                    n3 = n2 * n1;
                    stack.push(String.valueOf(n3));
                    break;
                case "/":
                    n1 = Integer.parseInt(stack.pop());
                    n2 = Integer.parseInt(stack.pop());
                    n3 = n2 / n1;
                    stack.push(String.valueOf(n3));
                    break;
                default:
                    stack.push(s);
            }
        }
        System.out.println("栈元素个数："+stack.size());
        System.out.println("结果为：" + stack.pop());
    }
}
